//
//  CLSeverTool.m
//  toroBracelet
//
//  Created by 丁益 on 16/7/20.
//  Copyright © 2016年 celi. All rights reserved.
//

#import "CLSeverTool.h"
#import "CLAlertView.h"

@implementation CLSeverTool
SingletonM(SeverTool)

+ (NSString *)getFilePath:(NSString *)fileName {
    
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *userDirectory = [[paths firstObject] stringByAppendingPathComponent:[self getUsedAccount]];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //创建文件夹
    if (![fileManager createDirectoryAtPath:userDirectory withIntermediateDirectories:YES attributes:nil error:nil]) {
        DLog(@"[error:] create database group.");
        return nil;
    }
    
    NSString *newFilePath = [userDirectory stringByAppendingPathComponent:fileName];
    if(![fileManager fileExistsAtPath:newFilePath]){ //如果不存在
        DLog(@"mainBudle %@  is not exist",fileName);
        NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"userInfo" ofType:@"plist"]; //获取程序包中相应文件的路径
        NSError *error;
        if([fileManager copyItemAtPath:plistPath toPath:newFilePath error:&error]) {
            DLog(@"copy mainBudle %@ success",fileName);
        } else {
            DLog(@"%@",error);
        }
    }
    return newFilePath;
}

+ (void)editSaveToPhotosFlag:(BOOL)flag{
    
    NSString *filePath = [CLSeverTool getFilePath:@"userInfo.plist"];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    [dict setValue:[NSNumber numberWithBool:flag] forKey:@"SaveToPhotos"];
    [dict writeToFile:filePath atomically:YES];
}

+ (BOOL)getSaveToPhotosFlag{
    
    NSString *filePath = [CLSeverTool getFilePath:@"userInfo.plist"];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    return [[dict objectForKey:@"SaveToPhotos"]boolValue];
}

+ (void)saveTokenToUserFile:(NSString *)nToken{
    
    NSString *filePath = [CLSeverTool getFilePath:@"userInfo.plist"];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    [dict setValue:nToken forKey:@"token"];
    [dict writeToFile:filePath atomically:YES];
}

+ (NSString *)getTokenFromUserFile{
    
    NSString *filePath = [CLSeverTool getFilePath:@"userInfo.plist"];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    return [dict objectForKey:@"token"];
}

+ (BOOL)saveUsedAccount:(NSString *)accountString{
    
    /*NSString *filePath = [CLSeverTool getFilePath:@"userInfo.plist"];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    [dict setObject:accountString forKey:@"usedAccounts"];
    return [dict writeToFile:filePath atomically:YES];*/
    
    // 写入文件
    [[NSUserDefaults standardUserDefaults] setObject: accountString forKey:@"usedAccounts"];
    
    return [[NSUserDefaults standardUserDefaults] synchronize];
}

+ (NSString *)getUsedAccount{
    
   /* NSString *filePath = [CLSeverTool getFilePath:@"userInfo.plist"];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    return [dict objectForKey:@"usedAccounts"];*/
    
    return [[NSUserDefaults standardUserDefaults] stringForKey:@"usedAccounts"];

}

+ (void)saveHasLoginStats:(BOOL)loginStats{
    
    NSString *isLoginKey = @"isLogin";
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //存储已成功登录过
    [defaults setBool:loginStats forKey:isLoginKey];
    [defaults synchronize];
}

+ (BOOL)getHasLoginStats{

    NSString *isLoginKey = @"isLogin";
    // 从沙盒中取出是否已经登录过
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL isLogin = [defaults boolForKey:isLoginKey];
    return isLogin;
}

+ (void)saveSettingProFileStats:(BOOL)settingProFileStats{
    NSString *SettingProFileStats = @"SettingProFile";
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //存储个人设置引导页
    [defaults setBool:settingProFileStats forKey:SettingProFileStats];
    [defaults synchronize];
}

+ (BOOL)getSettingProFileStats{
    NSString *SettingProFileStats = @"SettingProFile";
    // 从沙盒中取出是否已经登录过
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    BOOL stats = [defaults boolForKey:SettingProFileStats];
    return stats;
}




- (UIImage *)convertToGrayscale:(UIImage *)source {
    CGSize size = [source size];
    int width = size.width *source.scale;
    int height = size.height *source.scale;
    
    // the pixels will be painted to this array
    uint32_t *pixels = (uint32_t *) malloc(width * height * sizeof(uint32_t));
    
    // clear the pixels so any transparency is preserved
    memset(pixels, 0, width * height * sizeof(uint32_t));
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    // create a context with RGBA pixels
    CGContextRef context = CGBitmapContextCreate(pixels, width, height, 8, width * sizeof(uint32_t), colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedLast);
    
    // paint the bitmap to our context which will fill in the pixels array
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), source.CGImage);
    
    for(int y = 0; y < height; y++) {
        for(int x = 0; x < width; x++) {
            uint8_t *rgbaPixel = (uint8_t *) &pixels[y * width + x];
            
            // convert to grayscale using recommended method: http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
            uint32_t gray = 0.3 * rgbaPixel[RED] + 0.59 * rgbaPixel[GREEN] + 0.11 * rgbaPixel[BLUE];
            
            // set the pixels to gray
            rgbaPixel[RED] = gray;
            rgbaPixel[GREEN] = gray;
            rgbaPixel[BLUE] = gray;
        }
    }
    
    // create a new CGImageRef from our context with the modified pixels
    CGImageRef imageRef = CGBitmapContextCreateImage(context);
    
    // we're done with the context, color space, and pixels
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    free(pixels);
    
    // make a new UIImage to return
    UIImage *resultUIImage = [UIImage imageWithCGImage:imageRef
                                                 scale:source.scale
                                           orientation:UIImageOrientationUp];
    
    // we're done with image now too
    CGImageRelease(imageRef);
    
    return resultUIImage;
}

#pragma mark - 图片处理
// 图像压缩
+ (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}
//图像压缩方法二
+ (UIImage *)resizeImage:(UIImage *)srcImage toSize:(CGSize)dstSize
{
    CGImageRef imgRef = srcImage.CGImage;
    // the below values are regardless of orientation : for UIImages from Camera, width>height (landscape)
    CGSize  srcSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef)); // not equivalent to self.size (which is dependant on the imageOrientation)!
    
    /* Don't resize if we already meet the required destination size. */
    if (CGSizeEqualToSize(srcSize, dstSize)) {
        return srcImage;
    }
    
    CGFloat scaleRatio = dstSize.width / srcSize.width;
    UIImageOrientation orient = srcImage.imageOrientation;
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch(orient) {
            
        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;
            
        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(srcSize.width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;
            
        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(srcSize.width, srcSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, srcSize.height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;
            
        case UIImageOrientationLeftMirrored: //EXIF = 5
            dstSize = CGSizeMake(dstSize.height, dstSize.width);
            transform = CGAffineTransformMakeTranslation(srcSize.height, srcSize.width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI_2);
            break;
            
        case UIImageOrientationLeft: //EXIF = 6
            dstSize = CGSizeMake(dstSize.height, dstSize.width);
            transform = CGAffineTransformMakeTranslation(0.0, srcSize.width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI_2);
            break;
            
        case UIImageOrientationRightMirrored: //EXIF = 7
            dstSize = CGSizeMake(dstSize.height, dstSize.width);
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight: //EXIF = 8
            dstSize = CGSizeMake(dstSize.height, dstSize.width);
            transform = CGAffineTransformMakeTranslation(srcSize.height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        default:
            //[NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
            DLog(@"Invalid image orientation");
            return nil;
            
    }
    
    
    /////////////////////////////////////////////////////////////////////////////
    // The actual resize: draw the image on a new context, applying a transform matrix
    UIGraphicsBeginImageContextWithOptions(dstSize, NO, srcImage.scale);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -srcSize.height, 0);
    } else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -srcSize.height);
    }
    
    CGContextConcatCTM(context, transform);
    
    // we use srcSize (and not dstSize) as the size to specify is in user space (and we use the CTM to apply a scaleRatio)
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, srcSize.width, srcSize.height), imgRef);
    UIImage* resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resizedImage;
}


#pragma mark - alertView接口, 只在当前控制器显示alertView，不进行跳转操作,可以使用以下统一接口
/**
 *  显示alertView，并给定相应的操作
 *
 *  @param title       主标题
 *  @param message     副标题
 *  @param cancelTitle 取消按钮的标题
 *  @param okTitle     确定按钮的标题
 *  @param cancelBlock 取消按钮绑定的操作
 *  @param okBlock     确定按钮绑定的操作
 */
+ (void)showAlertViewInViewController:(UIViewController *)vc withTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelTitle okButtonTitle:(NSString *)okTitle cancelBlock:(void(^)())cancelBlock okBlock:(void(^)())okBlock
{
    if (SysVerValue >= 8) { // iOS8之后使用UIAlertController
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
        if (cancelTitle) { // 取消按钮
            [alert addAction:[UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:cancelBlock]];
        }
        
        if (okTitle) { // 确定按钮
            [alert addAction:[UIAlertAction actionWithTitle:okTitle style:UIAlertActionStyleDefault handler:okBlock]];
        }
        [vc presentViewController:alert animated:YES completion:nil];
        
    } else { // iOS8之前使用UIAlertView
        CLAlertView *alert = [[CLAlertView alloc] initWithTitle:title message:message cancelButtonTitle:cancelTitle okButtonTitles:okTitle cancelBlock:cancelBlock okBlock:okBlock];
        [alert show];
    }
}

/**
 *  只在当前控制器显示alertView，点击后没有界面跳转操作
 */
+ (void)showAlertViewWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelTitle okButtonTitle:(NSString *)okTitle cancelBlock:(void(^)())cancelBlock okBlock:(void(^)())okBlock
{
    CLAlertView *alert = [[CLAlertView alloc] initWithTitle:title message:message cancelButtonTitle:cancelTitle okButtonTitles:okTitle cancelBlock:cancelBlock okBlock:okBlock];
    [alert show];
}

/**
 *  只有一个点击事件，在上一个AlertView没消失之前只弹出一次
 */
+ (void)showAlertViewWithTitle:(NSString *)title  oneButtonTitle:(NSString *)oneButtonTitle oneBlock:(void (^)())oneBlock {
    
    CLAlertView *alert = [[CLAlertView alloc] initWithTitle:title message:nil cancelButtonTitle:oneButtonTitle okButtonTitles:nil cancelBlock:oneBlock okBlock:nil];
    [alert show];
}
/**
 *  只在当前控制器显示alertView,支持3个选择按钮，点击后没有界面跳转操作
 */
+ (void)showAlertViewWithTitle:(NSString *)title message:(NSString *)message cancelButtonTitle:(NSString *)cancelTitle oneButtonTitle:(NSString *)oneButtonTitle twoButtonTitle:(NSString *)twoButtonTitle cancelBlock:(void(^)())cancelBlock oneBlock:(void(^)())oneBlock twoBlock:(void(^)())twoBlock{
    
    CLAlertView *alert = [[CLAlertView alloc]initWithTitle:title message:message cancelButtonTitle:cancelTitle oneButtonTitles:oneButtonTitle twoButtonTitles:twoButtonTitle cancelBlock: cancelBlock oneBlock: oneBlock twoBlock:twoBlock];
    [alert show];
}

/**
 *  网络连接失败的提示框
 */
+ (void)showNetErrorAlert
{
    [self showAlertViewWithTitle:CLLocalizedString(@"NetError", nil) message:nil cancelButtonTitle:CLLocalizedString(@"OK", nil) okButtonTitle:nil cancelBlock:nil okBlock:nil];
}
/**
 *  显示message
 */
+ (void)showAlertWithMessage:(NSString *)message
{
    [self showAlertViewWithTitle:nil message:message cancelButtonTitle:CLLocalizedString(@"OK", nil) okButtonTitle:nil cancelBlock:nil okBlock:nil];
}
/**
 *  显示title
 */
+ (void)showAlertWithTitle:(NSString *)title
{
    [self showAlertViewWithTitle:title message:nil cancelButtonTitle:CLLocalizedString(@"OK", nil) okButtonTitle:nil cancelBlock:nil okBlock:nil];
}
/**
 *  显示title, message
 */
+ (void)showAlertWithTitle:(NSString *)title message:(NSString *)message
{
    [self showAlertViewWithTitle:title message:message cancelButtonTitle:CLLocalizedString(@"OK", nil) okButtonTitle:nil cancelBlock:nil okBlock:nil];
}

/**
 *  当返回结果r=400时，系统将会弹出重新登录对话框
 */
+ (BOOL) alertViewWithResponse:(NSDictionary*)responseObject{
    
    NSNumber *resultR = responseObject[@"r"];
    NSString *error = [NSString stringWithFormat:@"error%d",rAgainLogin];
    NSString *Title = CLLocalizedString(error, nil);
    if(resultR.integerValue == rAgainLogin){
        [CLSeverTool showAlertViewWithTitle:Title oneButtonTitle:CLLocalizedString(@"OK", nil) oneBlock:^{
            DLog(@"访问出问题了---------");
        }];
        return YES;
    }
    return NO;
}
@end
